#include "ImageInfo.h"



ImageInfo::ImageInfo (Ptr< QImage > pImage) : _pImage (pImage)
{

}



vector< int > ImageInfo::getGrayHistogram () const
{
	// calculate image's histogram
	vector< int > histogram (256, 0);
	int bytesPerLine = _pImage->bytesPerLine ();
	int bytesPerPixel = _pImage->depth () / 8;
	if (bytesPerPixel == 1) {
		// Calculate gray image's histogram
		for (int v = 0; v < _pImage->height (); ++v)
		{
			uchar * curLine = _pImage->scanLine (v);
			for (int u = 0; u < _pImage->width (); ++u)
				histogram[curLine[u]]++;
		}
	} else if (bytesPerPixel == 4) {
		// Image in RGB or ARGB
		for (int v = 0; v < _pImage->height (); ++v)
		{
			QRgb * curLine = (QRgb *)_pImage->scanLine (v);
			for (int u = 0; u < _pImage->width (); ++u)
				if (qAlpha (curLine[u]) != 0)
					histogram[qGray (curLine[u])]++;
		}
	} else {
		throw ("Image format unsupport");
	}
	return histogram;
}



vector< int > ImageInfo::getRedHistogram () const
{
	return getChannelHistogram (RED);
}



vector< int > ImageInfo::getGreenHistogram () const
{
	return getChannelHistogram (GREEN);
}



vector< int > ImageInfo::getBlueHistogram () const
{
	return getChannelHistogram (BLUE);
}



vector< int > ImageInfo::getChannelHistogram (int channel) const
{
	// calculate image's histogram
	vector< int > histogram (256, 0);
	int bytesPerLine = _pImage->bytesPerLine ();
	int bytesPerPixel = _pImage->depth () / 8;
	if (bytesPerPixel == 1) {
		return getGrayHistogram ();
	} else if (bytesPerPixel == 4) {
		// Image in RGB or ARGB
		for (int v = 0; v < _pImage->height (); ++v)
		{
			QRgb * curLine = (QRgb *)_pImage->scanLine (v);
			for (int u = 0; u < _pImage->width (); ++u)
				if (qAlpha (curLine[u]) != 0)
					histogram[((uchar *)&curLine[u])[channel]]++;
		}
	} else {
		throw ("Image format unsupport");
	}
	return histogram;
}

